package com.sun.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 缓存的配置信息
 */
@EnableConfigurationProperties(CacheProperties.class)
@EnableCaching
@Configuration
public class SpringCacheConfig {
    
    @Autowired
    private CacheProperties cacheProperties;


    /**
     * todo: 运行的原理：
     *    首先导入依赖：会自动导入相关配置信息：CacheAutoConfiguration -->指定缓存的类型redis-->RedisCacheConfiguration
     *      -->自动配制了RedisCacheManager-->>初始化所有缓存，每个缓存使用什么配置信息--> 如果RedisCacheConfiguration的配置信息已经有的
     *      就是用已有的，否则就是用默认的。--->想要改变默认的配置，只需要给容器中放入RedisCacheConfiguration即可 -->就会应用到RedisCacheManager中进行管理
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();

        if(redisProperties.getTimeToLive() != null){
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if(redisProperties.getKeyPrefix() != null){
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if(!redisProperties.isCacheNullValues()){
            config = config.disableCachingNullValues();
        }
        if(!redisProperties.isUseKeyPrefix()){
            config = config.disableKeyPrefix();
        }
        return config;
    }
}
